package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.article.entity.ApAuthor;
import com.usian.article.mapper.ApAuthorMapper;
import com.usian.article.service.IApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.AuthorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-09-30
 */
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements IApAuthorService {

    @Override
    public AuthorDto findByApUserId(Integer apUserId) {
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getUserId,apUserId);
        ApAuthor apAuthor = this.getOne(queryWrapper);
        if(apAuthor!=null){
            //查询到作者信息
            return BeanHelper.copyProperties(apAuthor,AuthorDto.class);
        }

        return null;
    }

    @Override
    public Integer saveApAuthor(AuthorDto dto) {
        //判断作者是否存在
        AuthorDto authorDto = this.findByApUserId(dto.getUserId());
        if(authorDto!=null){
            //文章作者已经存在
            throw new LeadException(AppHttpCodeEnum.DATA_EXIST,"文章作者已经存在");
        }

        //保存作者
        ApAuthor apAuthor = BeanHelper.copyProperties(dto, ApAuthor.class);
        apAuthor.setCreatedTime(new Date());
        boolean save = this.save(apAuthor);
        if(!save){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return apAuthor.getId();
    }

    @Override
    public ApAuthor findByWmUserId(Integer wmUserId) {
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getWmUserId,wmUserId);
        ApAuthor apAuthor = this.getOne(queryWrapper);
        if(apAuthor!=null){
            return apAuthor;
        }
        return null;
    }
}
